//
//  MyShowRegistrationViewController.m
//  BosidengIphone
//
//  Created by  on 11-12-30.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyShowRegistrationViewController.h"
#import "MyShowLoginViewController.h"
#import "MainViewController.h"
#import "AppDelegate.h"
#import "RegexKitLite.h"
#import "ASIFormDataRequest.h"

@implementation MyShowRegistrationViewController
@synthesize labNaviTitle;
@synthesize labTitle;
@synthesize labMessage;
@synthesize labNickname;
@synthesize labPhone;
@synthesize labPassword;
@synthesize labPasswordAgain;
@synthesize txtNickname;
@synthesize txtPhone;
@synthesize txtPassword;
@synthesize txtPasswordAgain;
@synthesize btnRegister;
@synthesize btnLogin;
@synthesize waitView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //self.labNaviTitle.text = [NSString stringWithFormat:@"立即秀一下 > 登录"];
    self.labTitle.text = [AppDelegate getLanguageString:@"show_regist_title"];
    self.labMessage.text = [AppDelegate getLanguageString:@"show_regist_message"];
    self.labNickname.text = [AppDelegate getLanguageString:@"show_regist_nickname"];
    self.labPhone.text = [AppDelegate getLanguageString:@"show_regist_phone"];
    self.labPassword.text = [AppDelegate getLanguageString:@"show_regist_password"];
    self.labPasswordAgain.text = [AppDelegate getLanguageString:@"show_regist_password_again"];
    [self.btnRegister setTitle:[AppDelegate getLanguageString:@"show_regist_title"] forState:UIControlStateNormal];
    [self.btnLogin setTitle:[AppDelegate getLanguageString:@"show_login_btn_message"] forState:UIControlStateNormal];
    txtNickname.text = @"";
    txtNickname.delegate = self;
    txtPhone.text = @"";
    txtPhone.delegate = self;
	txtPassword.text = @"";
    txtPassword.delegate = self;
    txtPasswordAgain.text = @"";
    txtPasswordAgain.delegate = self;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.labNaviTitle = nil;
    self.labTitle = nil;
    self.labMessage = nil;
    self.labNickname = nil;
    self.labPhone = nil;
    self.labPassword = nil;
    self.labPasswordAgain = nil;
    self.txtNickname = nil;
    self.txtPhone = nil;
    self.txtPassword = nil;
    self.txtPasswordAgain = nil;
    self.btnRegister = nil;
    self.btnLogin = nil;
    self.waitView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [labNaviTitle release];
    [labTitle release];
    [labMessage release];
    [labNickname release];
    [labPhone release];
    [labPassword release];
    [labPasswordAgain release];
    [txtNickname release];
    [txtPhone release];
    [txtPassword release];
    [txtPasswordAgain release];
    [btnRegister release];
    [btnLogin release];
    [waitView release];
    [super dealloc];
}

- (void)moveView:(UITextField *)textField slideUp:(BOOL)up {
    int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    //UIView *accessoryView = textField.inputAccessoryView;  
    //UIView *inputview     = textField.inputView;
    //NSLog(@"inputview=%.0f, accessoryView=%.0f", inputview.frame.size.height, accessoryView.frame.size.height);
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {  
    [self moveView:textField slideUp:YES];  
}  

- (void)textFieldDidEndEditing:(UITextField *)textField {  
    [self moveView:textField slideUp:NO];  
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    int tag = textField.tag;
    if (100 == tag) {
        [txtPhone becomeFirstResponder];
    } else if (101 == tag) {
        [txtPassword becomeFirstResponder];
    } else if (102 == tag) {
        [txtPasswordAgain becomeFirstResponder];
    } else {
        [textField resignFirstResponder];
    }
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	//NSLog(@"buttonIndex=%d", buttonIndex);
	[(MainViewController *)mainViewController popViewController];
}

- (IBAction)backgroundTab:(id)sender {
    [txtNickname resignFirstResponder];
    [txtPhone resignFirstResponder];
    [txtPassword resignFirstResponder];
    [txtPasswordAgain resignFirstResponder];
}

- (void)showCheckNullMessge:(NSString *)message {
	UIAlertView *infoView = [[UIAlertView alloc] 
							 initWithTitle:@""
							 message:[NSString stringWithFormat:@"%@%@", [AppDelegate getLanguageString:message], [AppDelegate getLanguageString:@"message_check_null"]]
							 delegate:nil 
							 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
							 otherButtonTitles:nil];
	[infoView show];
	[infoView release];
}

- (void)showCheckIllegalMessge:(NSString *)message {
	UIAlertView *infoView = [[UIAlertView alloc] 
							 initWithTitle:@""
							 message:[NSString stringWithFormat:@"%@%@", [AppDelegate getLanguageString:message], [AppDelegate getLanguageString:@"message_check_illegal"]]
							 delegate:nil 
							 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
							 otherButtonTitles:nil];
	[infoView show];
	[infoView release];
}

- (void)showMessge:(NSString *)message {
	UIAlertView *infoView = [[UIAlertView alloc] 
							 initWithTitle:@""
							 message:message
							 delegate:nil 
							 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
							 otherButtonTitles:nil];
	[infoView show];
	[infoView release];
}

- (IBAction)userRegister:(id)sender {
    NSString *nickname = txtNickname.text;
	if ([nickname isEqualToString:@""]) {
		[self showCheckNullMessge:@"show_regist_nickname"];
		return;
	}
	NSString *phone = txtPhone.text;
	if ([phone isEqualToString:@""]) {
		[self showCheckNullMessge:@"show_regist_phone"];
		return;
	}
	BOOL result = [phone isMatchedByRegex:@"\\b([0-9\\-]+)\\b"];
	if (!result) {
		[self showCheckIllegalMessge:@"show_regist_phone"];
		return;
	}
    
    NSString *password = txtPassword.text;
	if ([password isEqualToString:@""]) {
		[self showCheckNullMessge:@"show_regist_password"];
		return;
	}
    
    NSString *passwordAgain = txtPasswordAgain.text;
	if ([passwordAgain isEqualToString:@""]) {
		[self showCheckNullMessge:@"show_regist_password_again"];
		return;
	}

	if (![passwordAgain isEqualToString:password]) {
		[self showMessge:[AppDelegate getLanguageString:@"show_regist_password_not_same"]];
		return;
	}
	[waitView startAnimating];
	btnRegister.enabled = NO;
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/Register.ashx", [AppDelegate serviceUrl]]];
    ASIFormDataRequest *detectPost = [[ASIFormDataRequest alloc] initWithURL:url];
    [detectPost addPostValue:nickname forKey:@"txt_Nickname"];
    [detectPost addPostValue:phone forKey:@"txt_Account"];
    [detectPost addPostValue:password forKey:@"txt_Password"];
    [detectPost addPostValue:[AppDelegate getLanguage] forKey:@"txt_Language"];
    [detectPost setDelegate:self];
    [detectPost setDidFinishSelector:@selector(requestComplete:)];
    [detectPost setDidFailSelector:@selector(requestFailed:)];
    [requestQueue addOperation:detectPost];
	[detectPost release];
}

- (void)requestComplete:(ASIFormDataRequest *)request {
	NSString *result = [request responseString];
    if ([result rangeOfString:@"html"].length > 0) {
        [waitView stopAnimating];
        btnRegister.enabled = YES;
		[self showMessge:@"Regist Failed!"];
        NSLog(@"Regist Failed! result=%@", result);
        return;
    }
    
	NSArray *resultInfos = [result componentsSeparatedByString:@"|"];
    NSString *resultCode = [resultInfos objectAtIndex:0];
    NSString *resultMessage = [resultInfos objectAtIndex:1];
	if ([@"1" isEqualToString:resultCode]) {
        NSLog(@"Post Regist Request Success! result=%@", result);
        txtNickname.text = @"";
        txtPhone.text = @"";
		txtPassword.text = @"";
        txtPasswordAgain.text = @"";
        UIAlertView *infoView = [[UIAlertView alloc] 
                                 initWithTitle:@""
                                 message:resultMessage
                                 delegate:self 
                                 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
                                 otherButtonTitles:nil];
        [infoView show];
        [infoView release];
	} else {
		[self showMessge:resultMessage];
        NSLog(@"Post Regist Request Failed! result=%@", result);
	}
    [waitView stopAnimating];
	btnRegister.enabled = YES;
}

- (void)requestFailed:(ASIFormDataRequest *)request {
    [self showMessge:@"proposals_submit_failed"];
    NSLog(@"Post Request Failed! error=%@", [request error]);
    [waitView stopAnimating];
	btnRegister.enabled = YES;
}

- (IBAction)showLogin:(id)sender {
    [(MainViewController *)mainViewController popViewController];
    MyShowLoginViewController *viewController = [[MyShowLoginViewController alloc] initWithNibName:@"MyShowLoginViewController" bundle:nil];
    [(MainViewController *)mainViewController pushViewController:viewController];
    [viewController release];
}

@end
